package cz.schovjan.proj.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import cz.schovjan.proj.dao.IUserDao;
import cz.schovjan.proj.entity.UserEntity;
import cz.schovjan.proj.model.Constants.Roles;
import cz.schovjan.proj.model.User;
import cz.schovjan.proj.service.IUser;

/**
 * Implementace rozhrani IUser pro praci s uzivately.
 * @author schovjan
 * 
 */
@Transactional
public class UserImpl implements IUser {
	
	@Autowired
	private IUserDao userDao;
	

	@Override
	public List<User> findAll() {
		List<User> users = new ArrayList<User>();
		List<UserEntity> userEntitys = userDao.findAll();
		
		for (UserEntity ue : userEntitys) {
			users.add(loadUser(ue));
		}
		
		return users;
	}
	
	
	@Override
	public User find(String nick, String password) {
		return loadUser(userDao.findUser(nick, password));
	}

	
	/**
	 * Vrati nasetovaneho usera.
	 * @param ue
	 * @return
	 */
	private User loadUser(UserEntity ue) {
		if (ue==null) {
			return null;
		}
		
		return new User(ue.getNick(),
						ue.getName(),
						ue.getSurname(),
						ue.getPassword(),
						ue.getSign(),
						ue.getDateCreate(),
						ue.getEmail(),
						ue.getRole());
	}

	
	@Override
	public User add(String nick, String password, String name, String surname, String sign, String email) {
		UserEntity ue = new UserEntity();
		ue.setName(name);
		ue.setSurname(surname);
		ue.setNick(nick);
		ue.setPassword(password);
		ue.setRole(Roles.USER);
		ue.setSign(sign);
		ue.setEmail(email);
		ue.setDateCreate(new Date());

		userDao.add(ue);
		
		return find(nick, password);
	}
	
	
	@Override
	public boolean isExist(String nick) {
		
		return userDao.find(nick) == null ? false : true;
	}
	
	
	@Override
	public User find(String nick) {
		return loadUser(userDao.find(nick));
	}
	
	
	@Override
	public User save(String nick, String password, String name, String surname,	String sign, String email) {
		UserEntity ue = userDao.find(nick);
		ue.setName(name);
		ue.setSurname(surname);
		ue.setPassword(password);
		ue.setSign(sign);
		ue.setEmail(email);
		
		return find(nick, password);
	}
	
	
	@Override
	public void delete(String nick) {
		userDao.delete(nick);
	}
	
}
